package com.xoa.service.hr.impl;

import com.xoa.dao.common.HrCodeMapper;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.hr.HrStaffContractMapper;
import com.xoa.dao.hr.HrStaffInfoMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.BBS.BbsCommentWithBLOBs;
import com.xoa.model.common.HrCode;
import com.xoa.model.common.SysCode;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.hr.HrStaffContract;
import com.xoa.model.hr.HrStaffContractWithBLOB;
import com.xoa.model.hr.HrStaffInfo;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.users.UserPriv;
import com.xoa.model.users.Users;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.service.hr.HrStaffContractService;
import com.xoa.service.sms.SmsService;
import com.xoa.service.users.UsersService;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 创建作者:   高亚峰
 * 创建日期:   2017/7/13 17:09
 * 类介绍  :
 * 构造参数:
 */
@Service
public class HrStaffContractServiceImpl implements HrStaffContractService {
    @Resource
    private HrStaffContractMapper hrStaffContractMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private UserPrivMapper userPrivMapper;
    @Resource
    private HrStaffInfoMapper hrStaffInfoMapper;
    @Resource
    private EnclosureService enclosureService;
    @Resource
    private UsersService usersService;
    @Resource
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private HrCodeMapper hrCodeMapper;

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private SmsService smsService;
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年7月13日 下午16:40:41
     * 方法介绍:   查询和同详情
     * 参数说明:   ContractId 合同自动递增Id
     *
     * @return HrStaffContract
     */
    @Override
    public ToJson<HrStaffContract> getcontractinfo(HttpServletRequest request,String contractId) {
        ToJson<HrStaffContract> json = new ToJson<HrStaffContract>();
        if (contractId != null) {
            try {
                HrStaffContract getcontractinfo = hrStaffContractMapper.getcontractinfo(Integer.valueOf(contractId));

                //附件处理
                List<Attachment> attachmentList=new ArrayList<Attachment>();
                if(getcontractinfo.getAttachmentName()!=null&&!"".equals(getcontractinfo.getAttachmentName())){
                    attachmentList= GetAttachmentListUtil.returnAttachment(getcontractinfo.getAttachmentName(),getcontractinfo.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_HRSTAFFCONTRACT);
                }
                getcontractinfo.setAttachmentList(attachmentList);


                if (getcontractinfo != null) {
                    // 合同
                    if(getcontractinfo.getContractType()!=null){
                        SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("HR_STAFF_CONTRACT1", getcontractinfo.getContractType());
                        if (hr_staff_contract1 != null) {
                            getcontractinfo.setContractTypeName(hr_staff_contract1.getCodeName());
                        } else {
                            getcontractinfo.setContractTypeName("该合同类型不存在");
                        }
                    }

                    // 公司
                    if(getcontractinfo.getContractEnterpries()!=null){
                        SysCode hr_enterprise = sysCodeMapper.getSingleCode("HR_ENTERPRISE", getcontractinfo.getContractEnterpries());
                        if (hr_enterprise != null) {
                            getcontractinfo.setContractEnterpriesName(hr_enterprise.getCodeName());
                        } else {
                            getcontractinfo.setContractEnterpriesName("该公司不存在");
                        }
                    }
                    // 用户
                    Users usersBybyname = usersMapper.getUsersByuserId(getcontractinfo.getUserName());
                    if (usersBybyname != null) {
                        getcontractinfo.setUserName(usersBybyname.getUserName());
                        getcontractinfo.setStaffName(usersBybyname.getUserId());
                        getcontractinfo.setUserPriv(String.valueOf(usersBybyname.getUserPriv()));
                        getcontractinfo.setUserPrivName(usersBybyname.getUserPrivName());
                        String deptNameByDeptId = departmentMapper.getDeptNameByDeptId(usersBybyname.getDeptId());
                        getcontractinfo.setDeptName(deptNameByDeptId);
                    } else {
                        getcontractinfo.setUserName("");
                        getcontractinfo.setStaffName("");
                        getcontractinfo.setUserPrivName("");
                    }
                    // 提醒人员
                    if (!StringUtils.checkNull(getcontractinfo.getRemindUser())) {
                        String[] split = getcontractinfo.getRemindUser().split(",");
                        List<Users> usersByBynames = usersMapper.getUsersByUserIds(split);
                        StringBuffer sb = new StringBuffer();
                        for (Users u : usersByBynames) {
                            sb.append(u.getUserName() + ",");
                        }
                        getcontractinfo.setRemindUserName(sb.toString());
                    }
                }
                json.setFlag(0);
                json.setObject(getcontractinfo);
                json.setMsg("ok");
            } catch (Exception e) {
                json.setFlag(1);
                json.setMsg("err");
                e.printStackTrace();
            }
        }
        return json;
    }
    /**
     * 创建作者:   季佳伟
     * 创建日期:   2017年11月17日 上午11:30:41
     * 方法介绍:   查询登录人的合同详情
     * 参数说明:   ContractId 合同自动递增Id
     * @return    HrStaffContract
     */
    public ToJson<HrStaffContract> getContractInfoByStaffName(Users user){
        ToJson<HrStaffContract> json = new ToJson<HrStaffContract>();
        try {
            Users users = usersMapper.selectUserByUId(user.getUid());
            List<HrStaffContract> contract = hrStaffContractMapper.getContractInfoByStaffName(users.getByname());
            Integer allCount = hrStaffContractMapper.getAllCount();
            for (HrStaffContract hrSt : contract) {
                if(hrSt.getProbationEffectiveDate()==null){
                    hrSt.setProbationEffectiveDate(DateFormat.getDate("0000-00-00"));
                }
                if (hrSt.getUserName() != null && hrSt.getUserName() != "") {
                    // 合同
                    if (hrSt.getContractType() != null) {
                        SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("HR_STAFF_CONTRACT1", hrSt.getContractType());
                        if (hr_staff_contract1 != null) {
                            hrSt.setContractTypeName(hr_staff_contract1.getCodeName());
                        } else {
                            hrSt.setContractTypeName("该合同类型不存在");
                        }
                    } else {
                        hrSt.setContractTypeName("该合同类型不存在");
                    }

                    if (hrSt.getContractEnterpries() != null) {
                        // 公司
                        SysCode hr_enterprise = sysCodeMapper.getSingleCode("HR_ENTERPRISE", hrSt.getContractEnterpries());
                        if (hr_enterprise != null) {
                            hrSt.setContractEnterpriesName(hr_enterprise.getCodeName());
                        } else {
                            hrSt.setContractEnterpriesName("该公司不存在");
                        }
                    } else {
                        hrSt.setContractEnterpriesName("该公司不存在");
                    }

                    Users usersBybyname = usersMapper.getUsersByuserId(hrSt.getUserName());
                    if (usersBybyname != null) {
                        hrSt.setUserName(usersBybyname.getUserName());
                        HrStaffInfo wordJobByUserId = hrStaffInfoMapper.getStaffByUserId(usersBybyname.getUserId());
                        String deptNameByDeptId = departmentMapper.getDeptNameByDeptId(usersBybyname.getDeptId());
                        if(deptNameByDeptId!=null){
                            hrSt.setDeptName(deptNameByDeptId);
                        }
                        if(wordJobByUserId!=null){
                            if(wordJobByUserId.getWorkJob()!=null && wordJobByUserId.getWorkJob()!=""){
                                SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("WORK_JOB", wordJobByUserId.getWorkJob());
                                if(hr_staff_contract1!=null){
                                    hrSt.setPostName(hr_staff_contract1.getCodeName());
                                }else{
                                    hrSt.setPostName("");
                                }
                            }else{
                                hrSt.setPostName("");
                            }
                        }else{
                            hrSt.setPostName("");
                        }
                    } else {
                        hrSt.setUserName("该用户已被删除");
                        hrSt.setDeptName("");
                        hrSt.setPostName("");
                    }
                } else {
                    hrSt.setUserName("");
                    hrSt.setDeptName("");
                    hrSt.setPostName("");
                }
            }
            json.setTotleNum(allCount);
            json.setMsg("ok");
            json.setFlag(0);
            json.setObj(contract);
        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg("err");
            json.setObj(null);
        }
        return json;
    }

    @Override
    public BaseWrapper getHrCountByType() {
        BaseWrapper baseWrapper = new BaseWrapper();
        List<HrStaffContract> news = hrStaffContractMapper.getHrCountByType();
        Map<String,Integer> temp = new HashMap<>();
        List<SysCode> sysCodes= sysCodeMapper.getChildCode("HR_STAFF_CONTRACT1");
        for (SysCode sysCode:sysCodes){
            temp.put(sysCode.getCodeName(),0);
        }

        for(HrStaffContract item : news){
            String key = "合同类型";
            SysCode code = item.getCodes();
            if(code!=null){
                key = code.getCodeName();
            }
            if(temp.containsKey(key)){
                temp.put(key,temp.get(key)+1);
            }else{
                temp.put(key,1);
            }
        }
        baseWrapper.setData(temp);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }


    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年7月13日 下午17:23:41
     * 方法介绍:   合同信息修改
     * 参数说明:   HrStaffContract 参数
     *
     * @return ToJson
     */
    @Override
    public ToJson<Object> updateContractInfo(HttpServletRequest request,HrStaffContract hrStaffContract, String userPriv) {
        ToJson<Object> json = new ToJson<Object>();
        try {
            Date date =new Date();
            hrStaffContract.setLastUpdateTime(date);
            hrStaffContract.setUserName(hrStaffContract.getStaffName());
            hrStaffContractMapper.updateContractInfo(hrStaffContract);
            if (!StringUtils.checkNull(hrStaffContract.getStaffName())) {
                Users userByName = usersMapper.findUserByName(hrStaffContract.getStaffName());
                if(userByName!=null){

                if (!StringUtils.checkNull(userPriv)) {
                    userByName.setUserPriv(Integer.valueOf(userPriv));
                }
                    if(hrStaffContract.getJobId()!=null){
                        userByName.setJobId(hrStaffContract.getJobId());
                    }
                    if(hrStaffContract.getPostId()!=null){
                        userByName.setPostId(hrStaffContract.getPostId());
                    }
                    usersService.editUser(request,userByName, null, null);

                }
            }
            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {
            json.setFlag(1);
            json.setMsg("err");
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年7月13日 下午18:04:41
     * 方法介绍:   删除合同信息接口
     * 参数说明:    ContractId 合同自动递增Id
     *
     * @return ToJson
     */
    @Override
    public ToJson<Object> deleteContractInfo(String contractId) {
        ToJson<Object> json = new ToJson<Object>();
        if (contractId != null) {
            try {
                hrStaffContractMapper.deleteContractInfo(Integer.valueOf(contractId));
                json.setFlag(0);
                json.setMsg("ok");
            } catch (Exception e) {
                json.setFlag(1);
                json.setMsg("err");
                e.printStackTrace();
            }
        }
        return json;
    }

    @Override
    public ToJson<Object> piliangExport(HttpServletRequest request,HttpServletResponse response,String contractId,HrStaffContract hrStaffContract,String SignstartTime,String SignendTime,String TrialstartTime,String TrialendTime,String MaturitystartTime,String MaturityendTime,String RelievestartTime,String RelieveendTime) {
       ToJson toJson=new ToJson();
       try{
           //查询合同
//           List list=new ArrayList();
//           for(String s:contractId.split(",")){
//               list.add(s);
//           }
           String staffName=null;
           if (SignstartTime==null|| SignstartTime.equals("")) {
               SignstartTime = null;
           }
           if(hrStaffContract.getStaffName().equals("undefined") || hrStaffContract.getStaffName().equals("")){
               staffName=null;
           }
           if (SignendTime==null||SignendTime.equals("")) {
               SignendTime = null;
           }
           if (TrialstartTime==null||TrialstartTime.equals("")) {
               TrialstartTime = null;
           }
           if (TrialendTime==null||TrialendTime.equals("")) {
               TrialendTime = null;
           }
           if (MaturitystartTime==null||MaturitystartTime.equals("")) {
               MaturitystartTime = null;
           }
           if (MaturityendTime==null||MaturityendTime.equals("")) {
               MaturityendTime = null;
           }
           if (RelievestartTime==null||RelievestartTime.equals("")) {
               RelievestartTime = null;
           }
           if (RelieveendTime==null||RelieveendTime.equals("")) {
               RelieveendTime = null;
           }
           if (hrStaffContract.getContractType()==null||hrStaffContract.getContractType().equals("")) {
               hrStaffContract.setContractType(null);
           }

           ToJson<HrStaffContract> json = new ToJson<HrStaffContract>();
           Map<String, Object> map = new HashMap<String, Object>();
           if (!StringUtils.checkNull(hrStaffContract.getUserName())) {
               Users usersByname = usersMapper.getUsersByname(hrStaffContract.getUserName());
               if (usersByname != null) {
                   hrStaffContract.setUserName(usersByname.getByname());
               }
           }
           map.put("staffName",staffName);
           map.put("StaffContractNo", hrStaffContract.getStaffContractNo());
           map.put("ContractType", hrStaffContract.getContractType());
           map.put("ContractEnterpries", hrStaffContract.getContractEnterpries());
           map.put("contractSpecialization", hrStaffContract.getContractSpecialization());
           map.put("SignstartTime", SignstartTime);
           map.put("SignendTime", SignendTime);
           map.put("TrialstartTime", TrialstartTime);
           map.put("TrialendTime", TrialendTime);
           map.put("MaturitystartTime", MaturitystartTime);
           map.put("MaturityendTime", MaturityendTime);
           map.put("RelievestartTime", RelievestartTime);
           map.put("RelieveendTime", RelieveendTime);


           List<HrStaffContractWithBLOB> hrList=new ArrayList<>();
//          List<HrStaffContractWithBLOB> hrs=hrStaffContractMapper.getcontractinfoList(list);
           List<HrStaffContractWithBLOB> hrs = hrStaffContractMapper.getContractBLO(map);
           for(HrStaffContractWithBLOB hrStaffContractWithBLOB:hrs){
              if(hrStaffContractWithBLOB.getStaffName()!=null && !"".equals(hrStaffContractWithBLOB.getStaffName())){

                 Users user= usersMapper.getUserId(hrStaffContractWithBLOB.getStaffName());
                  if(user!=null){
                      hrStaffContractWithBLOB.setStaffUserName(user.getUserName());
                  }else{
                      hrStaffContractWithBLOB.setStaffUserName("");
                  }

              }

               if(hrStaffContractWithBLOB.getMakeContract()!=null){
                   hrStaffContractWithBLOB.setMakeContractStr(DateFormat.getStrDate(hrStaffContractWithBLOB.getMakeContract()));
               }
               if(hrStaffContractWithBLOB.getProbationEffectiveDate()!=null){
                   hrStaffContractWithBLOB.setProbationEffectiveDateStr(DateFormat.getStrDate(hrStaffContractWithBLOB.getProbationEffectiveDate()));
               }
               if(hrStaffContractWithBLOB.getContractEndTime()!=null){
                   hrStaffContractWithBLOB.setContractEndTimeStr(DateFormat.getStrDate(hrStaffContractWithBLOB.getContractEndTime()));
               }
               if(hrStaffContractWithBLOB.getIsTrial()!=null){
                   if("0".equals(hrStaffContractWithBLOB.getIsTrial())){
                       hrStaffContractWithBLOB.setIsTrialStr("不试用");
                   }else if ("1".equals(hrStaffContractWithBLOB.getIsTrial())){
                       hrStaffContractWithBLOB.setIsTrialStr("试用");
                   }

               }

               if(hrStaffContractWithBLOB.getRemoveOrNot()!=null){
                   if("0".equals(hrStaffContractWithBLOB.getRemoveOrNot())){
                       hrStaffContractWithBLOB.setRemoveOrNotStr("不解除");
                   }else if ("1".equals(hrStaffContractWithBLOB.getRemoveOrNot())){
                       hrStaffContractWithBLOB.setRemoveOrNotStr("解除");
                   }

               }
               if(hrStaffContractWithBLOB.getIsRenew()!=null){
                   if("0".equals(hrStaffContractWithBLOB.getIsRenew())){
                       hrStaffContractWithBLOB.setIsRenewStr("不续签");
                   }else if ("1".equals(hrStaffContractWithBLOB.getIsRenew())){
                       hrStaffContractWithBLOB.setIsRenewStr("续签");
                   }

               }
               if(hrStaffContractWithBLOB.getContractSpecialization()!=null){
                   if("1".equals(hrStaffContractWithBLOB.getContractSpecialization())){
                       hrStaffContractWithBLOB.setContractSpecializationStr("固定期限");
                   }else if("2".equals(hrStaffContractWithBLOB.getContractSpecialization())){
                       hrStaffContractWithBLOB.setContractSpecializationStr("无固定期限");
                   }else if("3".equals(hrStaffContractWithBLOB.getContractSpecialization())){
                       hrStaffContractWithBLOB.setContractSpecializationStr("以完成一定工作任务为期限");
                   }
               }
               if(hrStaffContractWithBLOB.getContractEnterpries()!=null){

                   SysCode sysCode= sysCodeMapper.getSingleCode("HR_ENTERPRISE",hrStaffContractWithBLOB.getContractEnterpries());
                   hrStaffContractWithBLOB.setContractEnterpriesName(sysCode.getCodeName());
               }else{
                   hrStaffContractWithBLOB.setContractEnterpriesName("");
               }


               if(hrStaffContractWithBLOB.getContractType()!=null){

                   SysCode sysCode= sysCodeMapper.getSingleCode("HR_STAFF_CONTRACT1",hrStaffContractWithBLOB.getContractType());
                   hrStaffContractWithBLOB.setContractTypeName(sysCode.getCodeName());
               }

               if(!"".equals(hrStaffContract.getRemindUser())){
                   String userName="";
                   for(String userId:hrStaffContractWithBLOB.getRemindUser().split(",")){
                       userName+= usersMapper.getUsernameByUserId(userId);

                   }
                   if(!userName.equals(null)) {
                       hrStaffContractWithBLOB.setRemindUserName(userName);
                   }else{
                       hrStaffContractWithBLOB.setRemindUserName("");
                   }

               }else{
                   hrStaffContractWithBLOB.setRemindUserName("");
               }
           }
           HSSFWorkbook workbook2 = new HSSFWorkbook();
           workbook2.createSheet();
           String[] secondTitles = {"姓名","合同编号",     "合同签约公司名称",      "合同类型名称",    "合同期限属性", "角色",     "合同签订日期",            "合同生效日期",     "合同终止日期",    "是否含试用期",      "合同是否已解除",     "合同是否续签",  "提醒人员",  "备注"};
           HSSFSheet sheet = workbook2.getSheetAt(0);
           HSSFRow rowField = sheet.createRow(1);
           for (int i = 0; i < secondTitles.length; i++) {
               HSSFCell cell = rowField.createCell(i);
               cell.setCellValue(secondTitles[i]);
           }
           // String[] beanProperty = {user.getDep().getDeptName(),"userName","userPrivName", "roleAuxiliaryName","online","sex","online","telNoDept","telNoDept","departmentPhone","email"};
           String[] beanProperty = {"staffUserName","staffContractNo", "contractEnterpriesName","contractTypeName", "contractSpecializationStr","userPrivName", "makeContractStr",     "probationEffectiveDateStr",   "contractEndTimeStr",     "isTrialStr","removeOrNotStr", "isRenewStr","remindUserName","remark"};

           HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, hrs, beanProperty);
           ServletOutputStream out = response.getOutputStream();

           String filename = "合同管理.xls";
           filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
           response.setContentType("application/vnd.ms-excel");
           response.setHeader("content-disposition", "attachment;filename=" + filename);
          workbook.write(out);
           out.close();


           toJson.setMsg("true");
           toJson.setFlag(0);
       }catch (Exception e){
           toJson.setMsg(e.getMessage());
           toJson.setFlag(1);
       }
       return  toJson;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年7月14日 上午10:28:04
     * 方法介绍:   查询合同列表接口
     * 参数说明:
     *
     * @return HrStaffContract
     */
    @Override
    public ToJson<HrStaffContract> getAllContract(Integer page, Integer pageSize, boolean useFlag,String userId) {
        ToJson<HrStaffContract> json = new ToJson<HrStaffContract>();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", pageParams);
        map.put("userId",userId);
        try {
            List<HrStaffContract> allContract = hrStaffContractMapper.getAllContract(map);
            //Integer allCount = hrStaffContractMapper.getAllCount();
            for (HrStaffContract hrSt : allContract) {
                if(hrSt.getProbationEffectiveDate()==null){
                    hrSt.setProbationEffectiveDate(DateFormat.getDate("0000-00-00"));
                }
                if (hrSt.getUserName() != null && hrSt.getUserName() != "") {
                    // 合同
                    if (hrSt.getContractType() != null) {
                        SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("HR_STAFF_CONTRACT1", hrSt.getContractType());
                        if (hr_staff_contract1 != null) {
                            hrSt.setContractTypeName(hr_staff_contract1.getCodeName());
                        } else {
                            hrSt.setContractTypeName("该合同类型不存在");
                        }
                    } else {
                        hrSt.setContractTypeName("该合同类型不存在");
                    }

                    if (hrSt.getContractEnterpries() != null) {
                        // 公司
                        SysCode hr_enterprise = sysCodeMapper.getSingleCode("HR_ENTERPRISE", hrSt.getContractEnterpries());
                        if (hr_enterprise != null) {
                            hrSt.setContractEnterpriesName(hr_enterprise.getCodeName());
                        } else {
                            hrSt.setContractEnterpriesName("该公司不存在");
                        }
                    } else {
                        hrSt.setContractEnterpriesName("该公司不存在");
                    }

                    Users usersBybyname = usersMapper.getUsersByuserId(hrSt.getUserName());
                    if (usersBybyname != null) {
                        hrSt.setUserName(usersBybyname.getUserName());
                        HrStaffInfo wordJobByUserId = hrStaffInfoMapper.getStaffByUserId(usersBybyname.getUserId());
                        String deptNameByDeptId = departmentMapper.getDeptNameByDeptId(usersBybyname.getDeptId());
                        if(deptNameByDeptId!=null){
                            hrSt.setDeptName(deptNameByDeptId);
                        }
                        if(wordJobByUserId!=null){
                        if(wordJobByUserId.getWorkJob()!=null && wordJobByUserId.getWorkJob()!=""){
                            SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("WORK_JOB", wordJobByUserId.getWorkJob());
                            if(hr_staff_contract1!=null){
                                hrSt.setPostName(hr_staff_contract1.getCodeName());
                            }else{
                                hrSt.setPostName("");
                            }
                        }else{
                            hrSt.setPostName("");
                        }
                        }else{
                            hrSt.setPostName("");
                        }
                    } else {
                        hrSt.setUserName("该用户已被删除");
                        hrSt.setDeptName("");
                        hrSt.setPostName("");
                    }
                } else {
                    hrSt.setUserName("");
                    hrSt.setDeptName("");
                    hrSt.setPostName("");
                }
            }
            json.setTotleNum(pageParams.getTotal());
            json.setMsg("ok");
            json.setFlag(0);
            json.setObj(allContract);
        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg("err");
            json.setObj(null);
        }
        return json;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年7月14日 上午10:53:04
     * 方法介绍:   合同管理新建接口
     * 参数说明:   HrStaffContract
     *
     * @return ToJson
     */
    @Override
    public ToJson<Object> addContract(HttpServletRequest request, HrStaffContract hrStaffContract, String userPriv) {
        //因为数据库所有字段的属性都不能未null,所以要处理一下
        if (hrStaffContract.getStaffName() == null) {
            hrStaffContract.setStaffName("");
        }
        if (hrStaffContract.getStaffContractNo() == null) {
            hrStaffContract.setStaffContractNo("");
        }
        if (hrStaffContract.getContractType() == null) {
            hrStaffContract.setContractType("");
        }
        if (hrStaffContract.getContractSpecialization() == null) {
            hrStaffContract.setContractSpecialization("");
        }
        if (hrStaffContract.getProbationaryPeriod() == null) {
            hrStaffContract.setProbationaryPeriod("");
        }
        if (hrStaffContract.getPassOrNot() == null) {
            hrStaffContract.setPassOrNot("");
        }
        if (hrStaffContract.getActivePeriod() == null) {
            hrStaffContract.setActivePeriod("");
        }
        if (hrStaffContract.getRemark() == null) {
            hrStaffContract.setRemark("");
        }
        if (hrStaffContract.getRemoveOrNot() == null) {
            hrStaffContract.setRemoveOrNot("");
        }
        if (hrStaffContract.getStatus() == null) {
            hrStaffContract.setStatus("");
        }
        if (hrStaffContract.getSingTimes() == null) {
            hrStaffContract.setSingTimes("");
        }
        if (hrStaffContract.getStaffUserName() == null) {
            hrStaffContract.setStaffUserName("");
        }
        if (hrStaffContract.getRemindUser() == null) {
            hrStaffContract.setRemindUser("");
        }
        if (hrStaffContract.getRemindType() == null) {
            hrStaffContract.setRemindType(0);
        }
        if (hrStaffContract.getHasReminded() == null) {
            hrStaffContract.setHasReminded(0);
        }
        if (hrStaffContract.getRenewTime() == null) {
            hrStaffContract.setRenewTime("");
        }
        if (hrStaffContract.getContractEnterpries() == null) {
            hrStaffContract.setContractEnterpries("");
        }
        if (hrStaffContract.getIsTrial() == null) {
            hrStaffContract.setIsTrial("");
        }
        if (hrStaffContract.getIsRenew() == null) {
            hrStaffContract.setIsRenew("");
        }
        if (hrStaffContract.getUserName() == null) {
            hrStaffContract.setUserName("");
        }
        if(hrStaffContract.getPostId()==null){
            hrStaffContract.setPostId(0);
        }
        if(hrStaffContract.getJobId()==null){
            hrStaffContract.setJobId(0);
        }
        ToJson<Object> json = new ToJson<Object>();
        try {
            Users userByName = null;
        if (!StringUtils.checkNull(hrStaffContract.getStaffName())) {
            userByName = usersMapper.findUserByName(hrStaffContract.getStaffName());
            if(userByName!=null){
                if (!StringUtils.checkNull(userPriv)) {
                userByName.setUserPriv(Integer.valueOf(userPriv));
                userByName.setPostId(hrStaffContract.getPostId());
                userByName.setJobId(hrStaffContract.getJobId());
                usersService.editUser(request,userByName, null, null);
                }
            }
        }
            //从session中获取创建者的信息
            Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);

            hrStaffContract.setCreateUserId(users.getUserId());
            hrStaffContract.setCreateDeptId(users.getDeptId());
            hrStaffContract.setUserName(hrStaffContract.getStaffName());
            Date date =new Date();
            //登记日期
            hrStaffContract.setAddTime(date);
            hrStaffContractMapper.addContract(hrStaffContract);
            if(userByName!=null){
                addAffairs(hrStaffContract,userByName.getUserId(),request);
            }

            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {
            json.setFlag(1);
            json.setMsg("err");
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年7月14日 下午15:24:04
     * 方法介绍:   查询试用到期的合同
     * 参数说明:   startTime 到期开始时间
     * 参数说明:   endTime 到期结束时间
     *
     * @return ToJson
     */
    @Override
    public ToJson<HrStaffContract> getTrialContract(String startTime, String endTime) {
        ToJson<HrStaffContract> json = new ToJson<HrStaffContract>();
        if (startTime == "") {
            startTime = null;
        }
        if (endTime == "") {
            endTime = null;
        }
        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            List<HrStaffContract> maturityContract = hrStaffContractMapper.getTrialContract(map);
            for (HrStaffContract hrStaffContract : maturityContract) {
                if (hrStaffContract.getUserName() != null) {
                    Users usersBybyname = usersMapper.getUsersByuserId(hrStaffContract.getUserName());
                    if (usersBybyname != null) {
                        hrStaffContract.setUserName(usersBybyname.getUserName());
                        HrStaffInfo wordJobByUserId = hrStaffInfoMapper.getStaffByUserId(usersBybyname.getUserId());
                        String deptNameByDeptId = departmentMapper.getDeptNameByDeptId(usersBybyname.getDeptId());
                        hrStaffContract.setDeptName(deptNameByDeptId);
                        if(wordJobByUserId!=null){
                            if(wordJobByUserId.getWorkJob()!=null && wordJobByUserId.getWorkJob()!=""){
                                SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("WORK_JOB", wordJobByUserId.getWorkJob());
                                if(hr_staff_contract1!=null){
                                    hrStaffContract.setPostName(hr_staff_contract1.getCodeName());
                                }else{
                                    hrStaffContract.setPostName("");
                                }
                            }else{
                                hrStaffContract.setPostName("");
                            }
                        }else{
                            hrStaffContract.setPostName("");
                        }
                    } else {
                        hrStaffContract.setUserName("");
                        hrStaffContract.setPostName("");
                        hrStaffContract.setDeptName("");
                    }
                } else {
                    hrStaffContract.setUserName("");
                }
            }
            json.setFlag(0);
            json.setMsg("ok");
            json.setObj(maturityContract);
        } catch (Exception e) {
            json.setMsg("err");
            json.setFlag(1);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年7月14日 下午16:24:04
     * 方法介绍:   查询合同到期的合同
     * 参数说明:   startTime 到期开始时间
     * 参数说明:   endTime 到期结束时间
     * 参数说明：   hrStaffContract
     *
     * @return ToJson
     */
    @Override
    public ToJson<HrStaffContract> getMaturityContract(HrStaffContract hrStaffContract, String startTime, String endTime) {
        if (startTime == "") {
            startTime = null;
        }
        if (endTime == "") {
            endTime = null;
        }
        ToJson<HrStaffContract> json = new ToJson<HrStaffContract>();
        Map<String, Object> map = new HashMap<String, Object>();
        if(hrStaffContract.getContractType()!=null&&hrStaffContract.getContractType()!=""){
        map.put("contractType",hrStaffContract.getContractType());
        }
        if(hrStaffContract.getIsRenew()!=null&&hrStaffContract.getIsRenew()!=""){
        map.put("IsRenew", hrStaffContract.getIsRenew());
        }
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        try {
            List<HrStaffContract> maturityContract = hrStaffContractMapper.getMaturityContract(map);
            for (HrStaffContract hrSt : maturityContract) {
                if (hrSt.getUserName() != null) {
                        Users usersBybyname = usersMapper.getUsersByuserId(hrSt.getUserName());
                        if(usersBybyname!=null){
                            HrStaffInfo wordJobByUserId = hrStaffInfoMapper.getStaffByUserId(usersBybyname.getUserId());
                            String deptNameByDeptId = departmentMapper.getDeptNameByDeptId(usersBybyname.getDeptId());
                            String userPrivNameByDeptId =userPrivMapper.getPrivNameById(usersBybyname.getUserPriv());
                            if (hrSt.getContractType() != null) {
                                SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("HR_STAFF_CONTRACT1", hrSt.getContractType());
                                if (hr_staff_contract1 != null) {
                                    hrSt.setContractTypeName(hr_staff_contract1.getCodeName());
                                } else {
                                    hrSt.setContractTypeName("该合同类型不存在");
                                }
                            } else {
                                hrSt.setContractTypeName("该合同类型不存在");
                            }
                            if (hrSt.getContractEnterpries() != null) {
                                // 公司
                                SysCode hr_enterprise = sysCodeMapper.getSingleCode("HR_ENTERPRISE", hrSt.getContractEnterpries());
                                if (hr_enterprise != null) {
                                    hrSt.setContractEnterpriesName(hr_enterprise.getCodeName());
                                } else {
                                    hrSt.setContractEnterpriesName("该公司不存在");
                                }
                            } else {
                                hrSt.setContractEnterpriesName("该公司不存在");
                            }
                            if (usersBybyname != null) {
                                hrSt.setUserName(usersBybyname.getUserName());
                                hrSt.setDeptName(deptNameByDeptId);
                                hrSt.setUserPriv(userPrivNameByDeptId);
                                if(wordJobByUserId!=null){
                                    if(wordJobByUserId.getWorkJob()!=null && wordJobByUserId.getWorkJob()!=""){
                                        SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("WORK_JOB", wordJobByUserId.getWorkJob());
                                        if(hr_staff_contract1!=null){
                                            hrSt.setPostName(hr_staff_contract1.getCodeName());
                                        }else{
                                            hrSt.setPostName("");
                                        }
                                    }else{
                                        hrSt.setPostName("");
                                    }
                                }else{
                                    hrSt.setPostName("");
                                }
                            } else {
                                hrSt.setUserName("");
                                hrSt.setDeptName("");
                                hrSt.setPostName("");
                                hrSt.setUserPriv("");
                            }
                        }
                } else {
                    hrSt.setUserName("");
                    hrSt.setDeptName("");
                    hrSt.setPostName("");
                    hrSt.setUserPriv("");
                }
            }
            json.setFlag(0);
            json.setMsg("ok");
            json.setObj(maturityContract);
        } catch (Exception e) {
            json.setFlag(1);
            json.setMsg("err");
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年7月14日 下午17:50:04
     * 方法介绍:   合同查询接口
     * 参数说明:   SignstartTime 签约开始时间
     * 参数说明:   SignendTime 到期结束时间
     * 参数说明:   TrialstartTime 试用到期开始时间
     * 参数说明:   TrialendTime 试用到期结束时间
     * 参数说明:   MaturitystartTime 合同到期开始时间
     * 参数说明:   MaturityendTime 合同到期结束时间
     * 参数说明:   RelievestartTime 合同解除开始时间
     * 参数说明:   RelieveendTime 合同解除结束时间
     * 参数说明：   hrStaffContract
     *
     * @return ToJson
     */
    @Override
    public ToJson<HrStaffContract> getContract(HrStaffContract hrStaffContract, String SignstartTime, String SignendTime, String TrialstartTime, String TrialendTime, String MaturitystartTime, String MaturityendTime, String RelievestartTime, String RelieveendTime, Integer page, Integer pageSize,boolean useFlag) {
        if (SignstartTime==null|| SignstartTime.equals("")) {
            SignstartTime = null;
        }
        if (SignendTime==null||SignendTime.equals("")) {
            SignendTime = null;
        }
        if (TrialstartTime==null||TrialstartTime.equals("")) {
            TrialstartTime = null;
        }
        if (TrialendTime==null||TrialendTime.equals("")) {
            TrialendTime = null;
        }
        if (MaturitystartTime==null||MaturitystartTime.equals("")) {
            MaturitystartTime = null;
        }
        if (MaturityendTime==null||MaturityendTime.equals("")) {
            MaturityendTime = null;
        }
        if (RelievestartTime==null||RelievestartTime.equals("")) {
            RelievestartTime = null;
        }
        if (RelieveendTime==null||RelieveendTime.equals("")) {
            RelieveendTime = null;
        }
        if (hrStaffContract.getContractType()==null||hrStaffContract.getContractType().equals("")) {
            hrStaffContract.setContractType(null);
        }

        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);

        ToJson<HrStaffContract> json = new ToJson<HrStaffContract>();
        Map<String, Object> map = new HashMap<String, Object>();
        if (!StringUtils.checkNull(hrStaffContract.getUserName())) {
            Users usersByname = usersMapper.getUsersByname(hrStaffContract.getUserName());
            if (usersByname != null) {
                hrStaffContract.setUserName(usersByname.getByname());
            }
        }
        map.put("page", pageParams);
        map.put("staffName", hrStaffContract.getStaffName());
        map.put("StaffContractNo", hrStaffContract.getStaffContractNo());
        map.put("ContractType", hrStaffContract.getContractType());
        map.put("ContractEnterpries", hrStaffContract.getContractEnterpries());
        map.put("contractSpecialization", hrStaffContract.getContractSpecialization());
        map.put("SignstartTime", SignstartTime);
        map.put("SignendTime", SignendTime);
        map.put("TrialstartTime", TrialstartTime);
        map.put("TrialendTime", TrialendTime);
        map.put("MaturitystartTime", MaturitystartTime);
        map.put("MaturityendTime", MaturityendTime);
        map.put("RelievestartTime", RelievestartTime);
        map.put("RelieveendTime", RelieveendTime);
        try {
            List<HrStaffContract> contract = hrStaffContractMapper.getContract(map);
           // Integer allCount = hrStaffContractMapper.getAllCountMap(map);
            for (HrStaffContract hrSt : contract) {

                if (hrSt.getContractType() != null) {
                    SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("HR_STAFF_CONTRACT1", hrSt.getContractType());
                    if (hr_staff_contract1 != null) {
                        hrSt.setContractTypeName(hr_staff_contract1.getCodeName());
                    } else {
                        hrSt.setContractTypeName("该合同类型不存在");
                    }
                } else {
                    hrSt.setContractTypeName("该合同类型不存在");
                }

                if (hrSt.getContractEnterpries() != null) {
                    // 公司
                    SysCode hr_enterprise = sysCodeMapper.getSingleCode("HR_ENTERPRISE", hrSt.getContractEnterpries());
                    if (hr_enterprise != null) {
                        hrSt.setContractEnterpriesName(hr_enterprise.getCodeName());
                    } else {
                        hrSt.setContractEnterpriesName("该公司不存在");
                    }
                } else {
                    hrSt.setContractEnterpriesName("该公司不存在");
                }

                if (!StringUtils.checkNull(hrSt.getUserName())) {
                    Users usersBybyname = usersMapper.getUsersByuserId(hrSt.getUserName());
                    if (usersBybyname != null) {
                        HrStaffInfo wordJobByUserId = hrStaffInfoMapper.getStaffByUserId(usersBybyname.getUserId());
                        String deptNameByDeptId = departmentMapper.getDeptNameByDeptId(usersBybyname.getDeptId());
                        hrSt.setUserName(usersBybyname.getUserName());
                        hrSt.setDeptName(deptNameByDeptId);
                        if(wordJobByUserId!=null){
                            if(wordJobByUserId.getWorkJob()!=null && wordJobByUserId.getWorkJob()!=""){
                                SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("WORK_JOB", wordJobByUserId.getWorkJob());
                                if(hr_staff_contract1!=null){
                                    hrSt.setPostName(hr_staff_contract1.getCodeName());
                                }else{
                                    hrSt.setPostName("");
                                }
                            }else{
                                hrSt.setPostName("");
                            }
                        }else{
                            hrSt.setPostName("");
                        }
                    } else {
                        hrSt.setUserName("");
                        hrSt.setDeptName("");
                        hrSt.setPostName("");
                    }
                } else {
                    hrSt.setUserName("");
                    hrSt.setDeptName("");
                    hrSt.setPostName("");
                }
            }
            json.setTotleNum(pageParams.getTotal());
            json.setFlag(0);
            json.setMsg("ok");
            json.setObj(contract);
        } catch (Exception e) {
            json.setFlag(1);
            json.setMsg("err");
            e.printStackTrace();
        }
        return json;


    }

    /**
     * @作者：张航宁
     * @时间：2017/7/25
     * @介绍：批量删除接口
     * @参数：ids
     */
    @Override
    public ToJson<HrStaffContract> deleteByIds(String ids) {
        ToJson<HrStaffContract> json = new ToJson<HrStaffContract>();
        try {
            if (!StringUtils.checkNull(ids)) {
                String[] split = ids.split(",");
                if (split != null && split.length > 0) {
                    hrStaffContractMapper.deleteByIds(split);
                }
            }
            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg("err");
        }
        return json;
    }

    /**
     * @作者: 杨超
     * @时间：2017/8/14
     * @介绍：查询
     * @return
     */
    public BaseWrapper getContractAnalysis(){
        BaseWrapper bw = new BaseWrapper();
        List<HrStaffContract> allContract = hrStaffContractMapper.getAllContract(null);
        Map<String,Integer> temp = new HashMap<>();

        for(HrStaffContract hs : allContract){
          if(temp.containsKey( hs.getContractType())) {
              temp.put(hs.getContractType(), temp.get(hs.getContractType())+1);
          }else{
              temp.put(hs.getContractType(),1);
          }
        }
        bw.setData(temp);
        bw.setFlag(true);
        bw.setStatus(true);
        return bw;
    }

    public List<HrStaffContract> getAllContractSelf(String userId){

        List<HrStaffContract> allContract = hrStaffContractMapper.getHrStaffContractList(userId);

        for (HrStaffContract hrSt : allContract) {
            if(hrSt.getProbationEffectiveDate()==null){
                hrSt.setProbationEffectiveDate(DateFormat.getDate("0000-00-00"));
            }
            if (hrSt.getUserName() != null && hrSt.getUserName() != "") {
                // 合同
                if (hrSt.getContractType() != null) {
                    SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("HR_STAFF_CONTRACT1", hrSt.getContractType());
                    if (hr_staff_contract1 != null) {
                        hrSt.setContractTypeName(hr_staff_contract1.getCodeName());
                    } else {
                        hrSt.setContractTypeName("该合同类型不存在");
                    }
                } else {
                    hrSt.setContractTypeName("该合同类型不存在");
                }

                if (hrSt.getContractEnterpries() != null) {
                    // 公司
                    SysCode hr_enterprise = sysCodeMapper.getSingleCode("HR_ENTERPRISE", hrSt.getContractEnterpries());
                    if (hr_enterprise != null) {
                        hrSt.setContractEnterpriesName(hr_enterprise.getCodeName());
                    } else {
                        hrSt.setContractEnterpriesName("该公司不存在");
                    }
                } else {
                    hrSt.setContractEnterpriesName("该公司不存在");
                }

                Users usersBybyname = usersMapper.getUsersByuserId(hrSt.getUserName());
                if (usersBybyname != null) {
                    hrSt.setUserName(usersBybyname.getUserName());
                    HrStaffInfo wordJobByUserId = hrStaffInfoMapper.getStaffByUserId(usersBybyname.getUserId());
                    String deptNameByDeptId = departmentMapper.getDeptNameByDeptId(usersBybyname.getDeptId());
                    if(deptNameByDeptId!=null){
                        hrSt.setDeptName(deptNameByDeptId);
                    }
                    if(wordJobByUserId!=null){
                        if(wordJobByUserId.getWorkJob()!=null && wordJobByUserId.getWorkJob()!=""){
                            SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("WORK_JOB", wordJobByUserId.getWorkJob());
                            if(hr_staff_contract1!=null){
                                hrSt.setPostName(hr_staff_contract1.getCodeName());
                            }else{
                                hrSt.setPostName("");
                            }
                        }else{
                            hrSt.setPostName("");
                        }
                    }else{
                        hrSt.setPostName("");
                    }
                } else {
                    hrSt.setUserName("该用户已被删除");
                    hrSt.setDeptName("");
                    hrSt.setPostName("");
                }
            } else {
                hrSt.setUserName("");
                hrSt.setDeptName("");
                hrSt.setPostName("");
            }
        }

        return allContract;
    }

    /**
     * 创建者：戚中校
     * 方法作用：根据条件查询数量
     * @param
     * @param deptId(传入的多个部门的编号)
     * @return 返回的json字符串中  nums是返回的结果的数量
     *
     */
    @Override
    public ToJson<HrStaffContract> selectNumByCon(HrStaffContract record, Integer[] deptId) {
        ToJson toJson = new ToJson();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            if (deptId != null && deptId.length > 0){
                map.put("deptId",deptId);
            }
            map.put("record",record);
            List<HrStaffContract> list = hrStaffContractMapper.selectNumByCon(map);

            for(HrStaffContract hrStaffContract:list){
                if(!StringUtils.checkNull(hrStaffContract.getContractType())){
                    if(hrStaffContract.getContractType()!=null){
                        SysCode hr_staff_contract1 = sysCodeMapper.getSingleCode("HR_STAFF_CONTRACT1", hrStaffContract.getContractType());
                        if (hr_staff_contract1 != null) {
                            hrStaffContract.setContractTypeName(hr_staff_contract1.getCodeName());
                        } else {
                            hrStaffContract.setContractTypeName("该合同类型不存在");
                        }
                    }
                }

                if(!StringUtils.checkNull(hrStaffContract.getRemoveOrNot())){
                  if(hrStaffContract.getRemoveOrNot().equals("0")){
                    hrStaffContract.setStatusName("生效中");
                  }else if(hrStaffContract.getRemoveOrNot().equals("1")){
                      hrStaffContract.setStatusName("已解除");
                  }else{
                      hrStaffContract.setStatusName("未知");
                  }
                }
                if(!StringUtils.checkNull(hrStaffContract.getContractSpecialization())){
                    if(hrStaffContract.getContractSpecialization().equals("1")){
                        hrStaffContract.setContractSpecializationName("有固期限");
                    }else if(hrStaffContract.getContractSpecialization().equals("2")){
                        hrStaffContract.setContractSpecializationName("无固期限");
                    }else {
                        hrStaffContract.setContractSpecializationName("其它");
                    }
                }



            }

            if(list.size() >= 0){
                toJson.setObj(list);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }else{
                toJson.setMsg("err");
                toJson.setFlag(1);
            }

        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }

    @Override
    public ToJson<HrStaffContract> getContract(String staffName, Integer page, Integer pageSize, boolean useFlag) {
        ToJson<HrStaffContract> json = new ToJson<HrStaffContract>();
        //分页
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        HashMap<String,Object> map = new HashMap();
        map.put("pageParams", pageParams);
        map.put("staffName",staffName);
        try{
            List<HrStaffContract> list=hrStaffContractMapper.getByStaffNameContract(map);
            if(list.size()>0){
                for(int i=0;i<list.size();i++) {
                    Users user = usersMapper.findUsersByuserId(list.get(i).getStaffName()); //根据 id 找名字
                    list.get(i).setStaffUserName(user.getUserName());
                    if(list.get(i).getContractType()!=null){
                        //合同类型
                        HrCode hr_staff_contract2 = hrCodeMapper.selectCode("HR_STAFF_CONTRACT1",list.get(i).getContractType());
                        if (hr_staff_contract2 != null) {
                            list.get(i).setContractTypeName(hr_staff_contract2.getCodeName());
                        } else {
                            list.get(i).setContractTypeName(" ");
                        }
                    }
                }

                json.setObj(list);
            }
            json.setTotleNum(hrStaffContractMapper.getByStaffNameContractCount(staffName));
            json.setMsg("true");
            json.setFlag(0);
        }catch (Exception e){
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }


    @Override
    public ToJson imporController(MultipartFile file, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        ToJson<HrStaffInfo> json = new ToJson<HrStaffInfo>();
        // 成功次数
        Integer successCount = 0;
        InputStream in=null;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            StringBuffer buffer=new StringBuffer();
            if(osName.toLowerCase().startsWith("win")){
                //sb=sb.append(rb.getString("upload.win"));
                //判断路径是否是相对路径，如果是的话，加上运行的路径
                String uploadPath = rb.getString("upload.win");
                if(uploadPath.indexOf(":")==-1){
                    //获取运行时的路径
                    String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                    //获取截取后的路径
                    String str2 = "";
                    if(basePath.indexOf("/xoa")!=-1){
                        //获取字符串的长度
                        int length = basePath.length();
                        //返回指定字符在此字符串中第一次出现处的索引
                        int index = basePath.indexOf("/xoa");
                        //从指定位置开始到指定位置结束截取字符串
                        str2=basePath.substring(0,index);
                    }
                    path = path.append(str2 + "/xoa");
                }
                path.append(uploadPath);
                buffer=buffer.append(rb.getString("upload.win"));
            }else{
                path=path.append(rb.getString("upload.linux"));
                buffer=buffer.append(rb.getString("upload.linux"));
            }

            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File filedir=new File(path.toString());
                    if (!filedir.exists()) {
                        filedir.mkdirs();
                    }
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append("\\"+newFileName).toString();
                    in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    HrStaffContract hrStaffContract=null;

                    for (int i = 1; i <= lastRowNum; i++) {
                        hrStaffContract =new HrStaffContract();
                        SysCode sysCode=new SysCode();
                        row = sheetObj.getRow(i);
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //姓名
                                            //根据userName得到userId
                                            String  userName=getCellValue(cell);
                                            if(userName!=null){
                                                Users users=usersMapper.getUserByName(userName);
                                                if(users!=null){
                                                    hrStaffContract.setStaffName(users.getUserId());
                                                    hrStaffContract.setUserName(users.getUserId());
                                                }else{
                                                    hrStaffContract.setStaffName("");
                                                }
                                            }
                                            break;
                                        case 1:
                                            //合同编号
                                            hrStaffContract.setStaffContractNo(getCellValue(cell));
                                            break;
                                        case 2:
                                            //合同签约公司名称
                                            sysCode.setParentNo("HR_ENTERPRISE");
                                            sysCode.setCodeName(getCellValue(cell));

                                            SysCode s=sysCodeMapper.getCodeNoByNameAndParentNo(sysCode);
                                            if(s!=null) {
                                                hrStaffContract.setContractEnterpries(s.getCodeNo());
                                            }else{
                                                hrStaffContract.setContractEnterpries("");
                                            }
                                            break;
                                        case 3:
                                            //合同类型名称
                                            sysCode.setParentNo("HR_STAFF_CONTRACT1");
                                            sysCode.setCodeName(getCellValue(cell));

                                            SysCode ss=sysCodeMapper.getCodeNoByNameAndParentNo(sysCode);
                                            if(ss!=null) {
                                                hrStaffContract.setContractType(ss.getCodeNo());
                                            }else{
                                                hrStaffContract.setContractType("");
                                            }
                                            break;
                                        case 4:
                                            //合同期限属性
                                            String contractSpecializationStr=getCellValue(cell);
                                            if("固定期限".equals(contractSpecializationStr)){
                                                hrStaffContract.setContractSpecialization("1");
                                            }else if("无固定期限".equals(contractSpecializationStr)){
                                                hrStaffContract.setContractSpecialization("2");
                                            }else if("以完成一定工作任务为期限".equals(contractSpecializationStr)){
                                                hrStaffContract.setContractSpecialization("3");
                                            }else{
                                                hrStaffContract.setContractSpecialization("");
                                            }
                                            break;
                                        case 5:
                                            // 角色
                                            String userPrivName=getCellValue(cell);
                                            UserPriv userPriv=userPrivMapper.getUserPrivByName(userPrivName);
                                            if(userPriv!=null){
                                                hrStaffContract.setUserPriv(String.valueOf(userPriv.getUserPriv()));
                                            }else{
                                                hrStaffContract.setUserPriv("");
                                            }
                                            break;
                                        case 6:
                                            //合同签订日期
                                            if(getCellValue(cell)!=null){
                                                hrStaffContract.setMakeContract(DateFormat.getDates(getCellValue(cell)));
                                            }

                                            break;
                                        case 7:
                                            //合同生效日期
                                            if(getCellValue(cell)!=null) {
                                                hrStaffContract.setProbationEffectiveDate(DateFormat.getDates(getCellValue(cell)));
                                            }
                                            break;
                                        case 8:
                                            // 合同终止日期
                                            if(getCellValue(cell)!=null){
                                            hrStaffContract.setContractEndTime(DateFormat.getDates(getCellValue(cell)));
                                            }
                                            break;
                                        case 9:
                                            // 是否含试用期
                                            if(getCellValue(cell)!=null){
                                                if("不试用".equals(getCellValue(cell))){
                                                    hrStaffContract.setIsTrial("0");
                                                }else if ("试用".equals(getCellValue(cell))){
                                                    hrStaffContract.setIsTrial("1");
                                                }
                                            }
                                            break;
                                        case 10:
                                            //合同是否已解除
                                            if("不解除".equals(getCellValue(cell))){
                                                hrStaffContract.setRemoveOrNot("0");
                                            }else if ("解除".equals(getCellValue(cell))){
                                                hrStaffContract.setRemoveOrNot("1");
                                            }
                                            break;
                                        case 11:
                                            // 合同是否续签
                                            if("不续签".equals(getCellValue(cell))){
                                                hrStaffContract.setIsRenew("0");
                                            }else if ("续签".equals(getCellValue(cell))){
                                                hrStaffContract.setIsRenew("1");
                                            }
                                            break;
                                        case 12:
                                            //备注
                                            hrStaffContract.setRemark(getCellValue(cell));
                                            break;

                                    }
                                }
                            }
                           //判断是导入还是修改
                            // hrStaffContractMapper.getContractImport(hrStaffContract);
                           // hrStaffContractMapper.insert
                            hrStaffContract.setCreateUserId(user.getUserId());
                            hrStaffContract.setCreateDeptId(user.getDeptId());
                            //因为数据库所有字段的属性都不能未null,所以要处理一下
                            if (hrStaffContract.getStaffName() == null) {
                                hrStaffContract.setStaffName("");
                            }
                            if (hrStaffContract.getStaffContractNo() == null) {
                                hrStaffContract.setStaffContractNo("");
                            }
                            if (hrStaffContract.getContractType() == null) {
                                hrStaffContract.setContractType("");
                            }
                            if (hrStaffContract.getContractSpecialization() == null) {
                                hrStaffContract.setContractSpecialization("");
                            }
                            if (hrStaffContract.getProbationaryPeriod() == null) {
                                hrStaffContract.setProbationaryPeriod("");
                            }
                            if (hrStaffContract.getPassOrNot() == null) {
                                hrStaffContract.setPassOrNot("");
                            }
                            if (hrStaffContract.getActivePeriod() == null) {
                                hrStaffContract.setActivePeriod("");
                            }
                            if (hrStaffContract.getRemark() == null) {
                                hrStaffContract.setRemark("");
                            }
                            if (hrStaffContract.getRemoveOrNot() == null) {
                                hrStaffContract.setRemoveOrNot("");
                            }
                            if (hrStaffContract.getStatus() == null) {
                                hrStaffContract.setStatus("");
                            }
                            if (hrStaffContract.getSingTimes() == null) {
                                hrStaffContract.setSingTimes("");
                            }
                            if (hrStaffContract.getStaffUserName() == null) {
                                hrStaffContract.setStaffUserName("");
                            }
                            if (hrStaffContract.getRemindUser() == null) {
                                hrStaffContract.setRemindUser("");
                            }
                            if (hrStaffContract.getRemindType() == null) {
                                hrStaffContract.setRemindType(0);
                            }
                            if (hrStaffContract.getHasReminded() == null) {
                                hrStaffContract.setHasReminded(0);
                            }
                            if (hrStaffContract.getRenewTime() == null) {
                                hrStaffContract.setRenewTime("");
                            }
                            if (hrStaffContract.getContractEnterpries() == null) {
                                hrStaffContract.setContractEnterpries("");
                            }
                            if (hrStaffContract.getIsTrial() == null) {
                                hrStaffContract.setIsTrial("");
                            }
                            if (hrStaffContract.getIsRenew() == null) {
                                hrStaffContract.setIsRenew("");
                            }
                            if (hrStaffContract.getUserName() == null) {
                                hrStaffContract.setUserName("");
                            }
                            successCount += hrStaffContractMapper.addContract(hrStaffContract);

                        }
                    }
                } else {
                    json.setMsg("file type error!");
                    json.setFlag(1);
                    return json;
                }
            }
            json.setTotleNum(successCount);
            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setFlag(1);
        } finally {
            try {
                if(in!=null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return json;
    }

    private String getCellValue(Cell cell) {

        Object value=null;
        switch (cell.getCellType()){
            case STRING:
                value = cell.getStringCellValue();
                break;
            case NUMERIC:
                value = (int)cell.getNumericCellValue();
                break;
            default:
                value = cell.getStringCellValue();
                break;
        }
        return String.valueOf(value);
    }

    public void addAffairs(HrStaffContract hrStaffContract, String toId,HttpServletRequest request) {
        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        final String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users()).getUserId();

        final String remind = request.getParameter("remind");
        final String smsRemind = request.getParameter("smsRemind");
        this.threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ContextHolder.setConsumerType("xoa" + sqlType);
                SmsBody smsBody = new SmsBody();
                smsBody.setFromId(userId);
                smsBody.setContent("您有新的合同通知！");
                Date date = new Date();
                long dateLong = date.getTime()/1000;
                String strDate = String.valueOf(dateLong);
                Integer dateInt = Integer.valueOf(strDate.trim());
                smsBody.setSendTime(dateInt);
                SysCode sysCode = new SysCode();
                sysCode.setCodeName("合同管理");
                sysCode.setParentNo("SMS_REMIND");
                SysCode codeNoByNameAndParentNo = sysCodeMapper.getCodeNoByNameAndParentNo(sysCode);
                if (codeNoByNameAndParentNo != null) {
                    smsBody.setSmsType(codeNoByNameAndParentNo.getCodeNo());
                }
                smsBody.setIsAttach("0");
                smsBody.setRemindUrl("/hr/page/contractDetail?contractId="+hrStaffContract.getContractId());
                String title =  "合同通知！";
                String context = "您好，您有新的合同待查阅！请及时查看！";
                smsService.saveSms(smsBody, toId, remind, smsRemind, title, context, sqlType);
            }
        });

    }
}
